package cn.ac.sec.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.ac.sec.model.User;

@RestController
public class LoginController {

//	@RequestMapping("/login")
//    public String login(HttpServletRequest request) {
//		String loginName = request.getParameter("userName");
//		String password = request.getParameter("password");
//		System.err.println(loginName+"=="+password);
//		Subject subject = SecurityUtils.getSubject();
//		UsernamePasswordToken token = new UsernamePasswordToken(loginName,password);
//		if (StringUtils.isNotEmpty(loginName) && StringUtils.isNotEmpty(password)) {
//			try{
//				subject.login(token);	
//				User user = (User)subject.getPrincipal();	
//				subject.getSession().setAttribute("DT_LOGIN_USER", user);
//			}catch(Exception ex){
//				return "redirect:/login";
//			}
//		}
//		return "shiro 登录测试成功";
//    }
	
	@PostMapping("/login")
    public Map<String, Object> login(HttpServletRequest request) {
		String loginName = request.getParameter("userName");
		String password = request.getParameter("password");
		System.err.println(loginName+"=="+password);
		Map<String, Object> map = new HashMap<>();
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(loginName,password);
		if (StringUtils.isNotEmpty(loginName) && StringUtils.isNotEmpty(password)) {
			try{
				subject.login(token);
				User user = (User)subject.getPrincipal();	
				subject.getSession().setAttribute("DT_LOGIN_USER", user);
				map.put("result", user);
				map.put("token", subject.getSession().getId());
			}catch(Exception ex){
				map.put("result", "fail");
			}
		} else {
			map.put("result", "fail");
		}
		return map;
    }
}
